package controller

import (
	"net/http"
	"ProductServer/model"
	"ProductServer/service"

	"github.com/gin-gonic/gin"

	"strconv"
)

var productServer = service.NewProductService()

//IndexGetAllProduct ..查看所有商品
func IndexGetAllProduct(c *gin.Context) {
	products := productServer.GetAllProduct(0, 20)
	if products == nil {
		c.HTML(http.StatusInternalServerError, "web/views/500.html", nil)
	}
	c.HTML(http.StatusOK, "web/views/layout.html", gin.H{
		"yield": products,
	})
}

//GetAllProduct ..查看所有商品
func GetAllProduct(c *gin.Context) {
	products := productServer.GetAllProduct(0, 20)
	if products == nil {
		c.HTML(http.StatusInternalServerError, "web/views/500.html", nil)
	}
	c.HTML(http.StatusOK, "web/views/view.html", gin.H{
		"productArray": products,
	})
}

//GetUpdateProduct 前往修改商品界面
func GetUpdateProduct(c *gin.Context) {
	sid := c.Query("id")
	id, err := strconv.ParseInt(sid, 10, 32)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "web/views/500.html", nil)
	}
	product := productServer.GetProductByID(uint32(id))
	c.HTML(http.StatusOK, "web/views/manager.html", product)
}

//GetAddProduct ..前往商品添加界面
func GetAddProduct(c *gin.Context) {
	c.HTML(http.StatusOK, "web/views/add.html", nil)
}

//PostAddProduct ..添加商品
func PostAddProduct(c *gin.Context) {
	product := &model.Product{}
	snum := c.Query("ProductNum")
	num, err := strconv.ParseInt(snum, 10, 32)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "web/views/500.html", nil)
	}
	product.ProductName = c.PostForm("ProductName")
	product.ProductImage = c.PostForm("ProductImage")
	product.ProductNum = uint32(num)
	product.ProductURL = c.PostForm("ProductURL")

	id := productServer.InsertProduct(product)
	if id == 0 {
		c.HTML(http.StatusInternalServerError, "web/views/500.html", nil)
	}
	c.Redirect(http.StatusPermanentRedirect, "/product/all")
}

//GetDeleteProduct ..删除商品
func GetDeleteProduct(c *gin.Context) {
	sid := c.Query("id")
	id, err := strconv.ParseInt(sid, 10, 32)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "web/views/500.html", nil)
	}
	if !productServer.DeleteProductByID(uint32(id)) {
		c.HTML(http.StatusInternalServerError, "web/views/500.html", nil)
	}
	c.Redirect(http.StatusPermanentRedirect, "/product/all")
}
